<template>
  <div class="manage-container device-manage">
    <div class="search-block">
      <h3>设备管理</h3>
      <div class="flex-row search-filters">
        <div class="flex-row">
          <el-form size="small" :inline="true" :model="formQuery">
            <el-form-item label="设备序列号" class="filter">
              <el-input
                v-model.trim="formQuery.form.serial_no"
                placeholder="请输入"
                maxLength="40"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="设备品牌" class="filter">
              <el-select v-model="formQuery.form.brand_id" clearable>
                <el-option
                  v-for="(item, index) in brandList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备型号" class="filter">
              <el-input
                v-model.trim="formQuery.form.model_name"
                placeholder="请输入"
                maxLength="40"
                clearable
              ></el-input
            ></el-form-item>
            <el-form-item label="所属单位" class="filter" v-if="userInfo.role_name === '超级管理员'">
              <el-select v-model="formQuery.form.unit_id" clearable>
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.unit_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系人" class="filter">
              <el-input
                v-model.trim="formQuery.form.contact_user"
                placeholder="请输入"
                maxLength="40"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
        </div>

        <div class="search-btns">
          <el-button plain @click="formQuery.clickReset">重置</el-button>
          <el-button type="primary" @click="formQuery.clickSearch">查询</el-button>
        </div>
      </div>
    </div>

    <div class="flex-col device-table">
      <div class="flex-row device-table-action">
        <el-button type="primary" @click="deviceAdd">新增设备</el-button>
        <el-button plain @click="clickExport">导出数据</el-button>
      </div>
      <div class="device-table-data">
        <comTable
          :loading="pagination.loading"
          :tableData="deviceList"
          :listCount="pagination.total"
          :pageSize="pagination.pageSize"
          :currentPage="pagination.currentPage"
          :userColumn="tableColumns()"
          @updatePage="handleCurrentChange"
          @sizePage="handleSizeChange"
        >
          <template #serial_no>
            <el-table-column label="设备序列号" minWidth="200">
              <template #default="scope">
                <span style="color: #1182fb; padding: 0 10px">{{ scope.row.serial_no }}</span>
              </template>
            </el-table-column>
          </template>
          <template #location>
            <el-table-column label="登记位置" minWidth="80">
              <template #default="location">
                <el-popover
                  trigger="click"
                  placement="left"
                  title="登记位置"
                  width="263"
                  popper-class="information123"
                  effect="light"
                >
                  <div
                    style="border-top: 1px solid rgba(0, 0, 0, 0.06); width: 100%; padding-top: 8px; line-height: 20px"
                  >
                    <div>
                      {{ location.row.addres }}
                    </div>
                    <div>经度：{{ location.row.longitude }}</div>
                    <div>纬度：{{ location.row.latitude }}</div>
                  </div>
                  <template #reference>
                    <div style="display: flex; align-items: center; justify-content: center">
                      <img src="@/assets/img/device/icon_location.png" alt="" />
                      <span style="padding: 0 10px; cursor: pointer">查看</span>
                    </div>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
          </template>
          <template #device_status>
            <el-table-column label="设备状态" minWidth="120">
              <template #default="scope">
                <p class="table-state">
                  <span
                    :style="
                      scope.row.status === 0
                        ? 'background: #2fb083;'
                        : scope.row.status === 1
                        ? 'background: #FF2A00;'
                        : scope.row.status === 2
                        ? 'background: #E8AF27;'
                        : 'background: #4F698C;'
                    "
                  ></span>
                  <i
                    :style="
                      scope.row.status === 0
                        ? 'color: #2fb083;'
                        : scope.row.status === 1
                        ? 'color: #FF2A00;'
                        : scope.row.status === 2
                        ? 'color: #E8AF27;'
                        : 'color: #4F698C;'
                    "
                    >{{ scope.row.device_status }}</i
                  >
                </p>
              </template>
            </el-table-column>
          </template>
          <template #action>
            <el-table-column label="操作" minWidth="150">
              <template #default="scope">
                <span class="text-btn--primary edit" @click="handleEdit(scope.row)">编辑</span>
                <span class="text-btn--warn" @click="handleDelete(scope.row)">删除</span>
              </template>
            </el-table-column>
          </template>
        </comTable>
      </div>
    </div>
    <!-- 弹窗  -->
    <deviceDialog
      v-if="dialogVisible"
      :dialogVisible="dialogVisible"
      :dialogTitle="dialogTitle"
      :serialNo="serialNo"
      :id="id"
      @closeDialog="clickDialog"
      @updateList="getdeviceList"
    ></deviceDialog>
    <!-- 删除确认 -->
    <el-dialog v-model="deleteVisible" :modal="false" width="20%" draggable>
      <span>删除之后要无法撤销，确定要删除吗？ </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteVisible = false" style="margin-right: 20px">取消</el-button>
          <el-button type="primary" @click="deleteConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {reactive, ref, onMounted} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import manageApi from '@/api/manage.ts';
import registerApi from '@/api/register.ts';
import comTable from '@/components/comTable/index.vue';
import deviceDialog from './components/deviceManageDialog.vue';

const brandList = ref([]); // 设备品牌
const dialogVisible = ref(false);
const dialogTitle = ref('');
const serialNo = ref('');
const id = ref<number>();
const deleteVisible = ref(false);
const userInfo = JSON.parse(localStorage.getItem('userInfo')) || '';

// 顶部查询栏相关
const formQuery = reactive({
  form: {},
  clickSearch: () => {
    getdeviceList(formQuery.form);
  },
  clickReset: () => {
    formQuery.form = {
      serial_no: '',
      brand_id: '',
      model_name: '',
      unit_id: '',
      contact_user: '',
    };
    getdeviceList();
  },
});
// 新增设备
const deviceAdd = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增设备';
};
// 导出
const clickExport = async () => {
  const exportUrl = `${import.meta.env.VITE_API_URL}/api/device/export`;
  const data = await axios({
    method: 'get',
    url: exportUrl,
    headers: {
      token: localStorage.getItem('token'),
    },
    data: formQuery.form,
    responseType: 'blob',
  });
  const url = window.URL.createObjectURL(new Blob([data.data]));
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', '设备列表.xlsx');
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(link.href); // 释放URL 对象
  document.body.removeChild(link);
  link = null;
};
// 编辑
const handleEdit = (item) => {
  dialogVisible.value = true;
  dialogTitle.value = '编辑';
  serialNo.value = item.serial_no;
  id.value = item.id;
};
// 删除
const handleDelete = (item: any) => {
  id.value = item.id;
  deleteVisible.value = !deleteVisible.value;
};
const deleteConfirm = () => {
  manageApi
    .deviceManageDelete({id: id.value})
    .then((res) => {
      if (res.status === 0) {
        ElMessage.success(res.message);
        getdeviceList();
        deleteVisible.value = !deleteVisible.value;
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 关闭弹窗
const clickDialog = () => {
  dialogVisible.value = !dialogVisible.value;
};
// 地理逆编码
const findLocation = (lnglat) =>
  new Promise((resolve, reject) => {
    let locationText;
    AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new AMap.Geocoder();
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          locationText = result.regeocode.formattedAddress;
          resolve(locationText);
        }
      });
    });
  });
// 获取单位列表
const companyList = ref([]);
const getCompanyList = () => {
  registerApi
    .getCompanyList()
    .then((res) => {
      companyList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 获取设备品牌列表
const getBrandList = () => {
  manageApi
    .deviceBrandList()
    .then((res) => {
      brandList.value = res.data;
    })
    .catch((err) => {
      throw err;
    });
};
// 获取列表数据
const deviceList = ref([]);
const getdeviceList = (params) => {
  pagination.loading = true;
  manageApi
    .deviceManageList(params)
    .then((res) => {
      if (res.status === 0) {
        deviceList.value = res.data.data;
        pagination.total = res.data.total;
        pagination.pageSize = res.data.per_page;
        pagination.currentPage = res.data.current_page;
        pagination.loading = false;
        let lnglat;
        for (let i = 0; i < deviceList.value.length; i++) {
          lnglat = [deviceList.value[i].longitude, deviceList.value[i].latitude];
          findLocation(lnglat)
            .then((data) => {
              deviceList.value[i].addres = data;
            })
            .catch((err) => {
              throw err;
            });
        }
      }
    })
    .catch((err) => {
      throw err;
    });
};
// 分页相关
const pagination = reactive({
  loading: false,
  total: 20,
  pageSize: 15,
  currentPage: 1,
});
const handleSizeChange = (e: any) => {
  pagination.pageSize = e.pageSize;
  getdeviceList({per_page: pagination.pageSize, ...formQuery.form});
};
const handleCurrentChange = (e: any) => {
  pagination.currentPage = e.currentPage;
  getdeviceList({page: pagination.currentPage, per_page: pagination.pageSize, ...formQuery.form});
};
// 表格表头

onMounted(() => {
  getdeviceList();
  getCompanyList();
  getBrandList();
});

const tableColumns = () => [
  {
    prop: 'serial_no',
    label: '设备序列号',
    slot: 'serial_no',
  },
  {
    prop: 'name',
    label: '设备名称',
    minWidth: 120,
  },
  {
    prop: 'brand_name',
    label: '设备品牌',
    minWidth: 80,
  },
  {
    prop: 'model_name',
    label: '设备型号',
    minWidth: 100,
  },
  {
    prop: 'unit_name',
    label: '所属单位',
    minWidth: 210,
  },
  {
    prop: 'contact_user',
    label: '联系人',
    minWidth: 120,
  },
  {
    prop: 'contact_mobile',
    label: '联系人电话',
    minWidth: 160,
  },
  {
    prop: 'created_at',
    label: '创建时间',
    minWidth: 160,
  },
  {
    slot: 'location',
    label: '登记位置',
  },
  {
    slot: 'device_status',
    label: '设备状态',
  },
  {
    prop: 'action',
    label: '操作',
    slot: 'action',
  },
];
</script>
<style lang="scss" scoped>
@import url('@/assets/css/manage.scss');
.device-manage {
  background-color: transparent;
  padding: 0;
}
.search {
  &-block {
    height: 125px;
    background-color: #fff;
    padding: 20px 30px;
    border-radius: 2px;
  }
  &-filters {
    margin-top: 20px;
    justify-content: space-between;
    color: #333333;
    font-size: 14px;
    .el-input {
      margin-left: 15px;
      width: 172px;
      height: 32px;
    }
    .el-select {
      margin-left: 15px;
      width: 172px;
      height: 32px;
    }
    .filter {
      margin-right: 40px;
    }
  }
  &-btns {
    align-self: end;
    align-content: flex-end;
  }
}
.device-table {
  width: 100%;
  height: calc(100% - 175px);
  box-sizing: border-box;
  padding: 30px;
  background-color: #fff;
  margin-top: 14px;
  &-action {
    justify-content: flex-end;
  }
  &-data {
    overflow: auto;
    height: calc(100% - 20px);
  }
}
.edit {
  margin-right: 20px;
}
.table-state {
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  span {
    width: 4px;
    height: 4px;
    border-radius: 100%;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
  }
  i {
    font-style: normal;
    margin: 0 12px;
  }
}
</style>
